package com.tdx.quick.api.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 数据库操作类，自动加载类路径下的 druid.xml 配置文件
 */
public class DBUtils {
    private static final Logger logger = LoggerFactory.getLogger(DBUtils.class);
    private static final String CONTEXT_PATH = "classpath:druid.xml";
    public static Map<String, DruidDataSource> dataSourceMap;

    static {
        // 自动加载配置
        init();
    }

    /**
     * 初始化数据库连接池
     */
    public static void init() {
        // 初始化数据库连接池
        logger.info("初始化数据库连接池...");
        try {
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(CONTEXT_PATH);
            dataSourceMap = context.getBeansOfType(DruidDataSource.class);
            Runtime.getRuntime().addShutdownHook(new Thread(context::close));
            logger.info("初始化数据库连接池完毕");
        } catch (Exception e) {
            throw new RuntimeException("初始化数据库连接池异常", e);
        }
    }

    /**
     * 根据连接池名，获取数据源对象
     *
     * @param pool 连接池名
     * @return 数据源对象
     */
    public static DataSource getDataSource(String pool) {
        return dataSourceMap.get(pool);
    }
}
